package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AccessParams;
import com.alipay.api.domain.AlipayUserAgreementPageSignModel;
import com.alipay.api.request.AlipayUserAgreementPageSignRequest;
import com.alipay.api.response.AlipayUserAgreementPageSignResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import com.alipay.zxy.alipayplugin.message.response.AlipayUserAgreementSignDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author zxy
 * https://docs.alipay.com/pre-open/api_pre/alipay.user.agreement.page.sign
 */
@Slf4j
@Service
public class AlipayUserAgreementPageSignService extends BaseService {
    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayUserAgreementPageSignService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipayUserAgreementSignDTO agreement(AlipayUserAgreementPageSignModel alipayModel, String returnUrl) throws AlipayApiException, UnsupportedEncodingException {
        AlipayUserAgreementSignDTO signDTO;
        AccessParams accessParams = new AccessParams();
        accessParams.setChannel("ALIPAYAPP");
        alipayModel.setAccessParams(accessParams);
        alipayModel.setPersonalProductCode("GENERAL_WITHHOLDING_P");
        alipayConfig.setReturnUrl(returnUrl);
        AlipayUserAgreementPageSignRequest alipayRequest = new AlipayUserAgreementPageSignRequest();
        alipayRequest = (AlipayUserAgreementPageSignRequest) getAlipayRequest(alipayRequest, alipayConfig, alipayModel);
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        AlipayUserAgreementPageSignResponse alipayResponse = alipayClient.sdkExecute(alipayRequest);
        if (alipayResponse.isSuccess()) {
            log.info("支付宝签约返回值 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            signDTO = new AlipayUserAgreementSignDTO();
            signDTO.setAgreementUrl("alipays://platformapi/startapp?appId=60000157&appClearTop=false&startMultApp=YES&sign_params=" + URLEncoder.encode(alipayResponse.getBody(), "utf-8"));
            return signDTO;
        } else {
            log.info("支付宝签约错误 alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
            return null;
        }
    }
}
